<?php

namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\Db;
use think\Request;

use huobi\Huobi;


class ThirdController extends AdminBaseController
{

    public function market()
    {
        $size = 15;
        $data =  Db::name('spot_market')->where(['status' => 1])->order('platform asc ,sort desc')->paginate($size, false, ['query' => request()->param()]);
        $this->assign('datas', $data->items());
        $this->assign('num', $data->total());
        $this->assign('page', $data->render());
        return $this->fetch();
    }


    function syn(){
        set_time_limit(600);
        date_default_timezone_set("Etc/GMT");
        //加载接口
        Vendor("ccxt.ccxt");
        //$exchange_id = config('platforms')[$key];
        $exchange_class = "\\ccxt\\huobipro";
        $exchange = new $exchange_class();
        // echo $value[0];
        // exit;
        if ($exchange->has['fetchTicker']) {
            var_dump ($exchange->fetch_ticker('ETH_USTD')); // all tickers indexed by their symbols
        }


        exit;
        //获取所有market
        $rows = Db::name('spot_market')->where(['status' => 1])->select();
        if(empty($rows)){
            return json(['error'=>1,'msg'=>'没有需要更新的数据']);
        }
        $platforms= [];
        foreach ($rows as $key => $value) {
            $platforms[$value['platform']][]= $value['market'];
        }
        

        foreach ($platforms as $key => $value) {
            $exchange_id = config('platforms')[$key];
            $exchange_class = "\\ccxt\\$exchange_id";
            $exchange = new $exchange_class (array (
                'rateLimit' => 10000, // 统一的交易所属性
                'options' => array (
                    'adjustForTimeDifference' => true, // 特定交易所的属性
                ),
            ));
            // echo $value[0];
            // exit;
            if ($exchange->has['fetchTicker']) {
                var_dump ($exchange->fetch_ticker('ETH_USTD')); // all tickers indexed by their symbols
            }
        }
        print_r($platforms);
        return;
    }


    public function api()
    {
        $size = 15;
        $data =  Db::name('third_api')->where(['status' => 1])->whereOr(['status' => -1])->order('id desc')->paginate($size, false, ['query' => request()->param()]);
        $this->assign('datas', $data->items());
        $this->assign('num', $data->total());
        $this->assign('page', $data->render());
        return $this->fetch();
    }

    

    function addmarket()
    {
        if(request()->isPost()){
            $data      = input('param.');
            if(empty($data['platform'] || empty($data['stock']) || empty($stock['money']))){
                return $this->error('平台,交易币和结算币不能为空');
            }
            if($data['stock']==$data['money']){
                return $this->error('交易币和结算币不能相同');
            }
            $data['stock'] = strtoupper($data['stock']);
            $data['money'] = strtoupper($data['money']);
            $insert['market'] = $data['stock'].'/'.$data['money'];
            if(Db::name('spot_market')->where(['platform'=>$data['platform'],'market'=>$insert['market']])->count()>0){
                return $this->error('该平台已经有相同交易对');
            }

            $insert['platform']    = $data['platform'];
            $insert['market_name'] = $insert['market'];
            $insert['stock']       = $data['stock'];
            $insert['money']       = $data['money'];
            $insert['update_time']  = time();
            $result    = Db::name('spot_market')->field('platform,market,market_name,stock,money,update_time')->insert($insert);
            if ($result === false) {
                return $this->error(Db::name('spot_market')->getError());
            }
            return $this->success("添加成功！", url("third/market"));
        }
        $bizhong = Db::name('coin')->group('coin_symbol')->column('coin_symbol');
        $platforms  = config('platforms');
        $this->assign('platforms', $platforms);        
        $this->assign('coin', $bizhong);
        $this->assign('action',url('third/addmarket'));
        $this->assign('action_title','添加');
        return $this->fetch('edit_market');
    }



    public function editmarket()
    {   
        $id        = input('param.id/d');
        if($id<=0){
            return $this->error('非法操作');
        }
        if(request()->isPost()){
            $data      = input('param.');
            if(empty($data['platform'] || empty($data['stock']) || empty($stock['money']))){
                return $this->error('平台,交易币和结算币不能为空');
            }
            if($data['stock']==$data['money']){
                return $this->error('交易币和结算币不能相同');
            }
            $data['stock'] = strtoupper($data['stock']);
            $data['money'] = strtoupper($data['money']);
            $insert['market'] = $data['stock'].'/'.$data['money'];

            $map['platform'] = $data['platform'];
            $map['market']   = $insert['market'];
            $map['id']       = ['<>',$id];
            if(Db::name('spot_market')->where($map)->count()>0){
                return $this->error('该平台已经有相同交易对');
            }

            $insert['platform']    = $data['platform'];
            $insert['market_name'] = $insert['market'];
            $insert['stock']       = $data['stock'];
            $insert['money']       = $data['money'];
            $insert['update_time']  = time();
            $result    = Db::name('spot_market')->where('id',$id)->update($insert);
            if ($result === false) {
                return $this->error(Db::name('spot_market')->getError());
            }
            return $this->success("保存成功！", url("third/market"));
        }
        $data =  Db::name('spot_market')->where('id', $id)->find();
        $bizhong = Db::name('coin')->group('coin_symbol')->column('coin_symbol');
        $platforms  = config('platforms');
        $this->assign('platforms', $platforms);
        $this->assign('coin', $bizhong);
        $this->assign('data', $data);
        $this->assign('action',url('third/editmarket'));
        $this->assign('action_title','编辑');
        return $this->fetch('edit_market');
    }



   


    public function delMarket()
    {
        $id = $this->request->param('id', 0, 'intval');

        $result    = Db::name('spot_market')->where('id', $id)->update([
            'status' => 0
        ]);
        if ($result === false) {
            $this->error('删除失败，请重试！', url("Third/market"));
        } else {
            $this->success('删除成功！', url("Third/market"));
        }
    }



    public function listorderss()
    {
        if ($_POST) {
            foreach ($_POST['sort'] as $k => $v) {
                $status = Db::name('spot_market')->where(['id' => $k])->update([
                    'sort' => $v
                ]);
            }
            $this->success("排序更新成功！");
        }
    }

    function uptag()
    {
        if ($_POST) {
            $id = $this->request->param('id');
            $tag = $this->request->param('tag');
            $type = $this->request->param('type');
            $isdel = Db::name('spot_market')->where(['id' => $id])->update([$tag => $type]);
            if ($isdel !== false) {
                echo "修改成功！";
            } else {
                echo "修改失败！";
            }
        }
    }
}
